package internal

import (
	"wechat-push/config"
	"wechat-push/internal/model"
	"wechat-push/pkg/logger"
	"wechat-push/pkg/util"
)

func SendMorning() {
	// 获取token
	token, err := GetWechatToken()
	if err != nil {
		logger.Log.Error("GetWechatToken err:", err)
		return
	}
	// 遍历users
	for _, user := range config.Cfg.Users {
		if !user.IsUsed {
			continue
		}
		// 组装数据
		data, err := FormatMorningData(user.Name, user.Region, user.City)
		if err != nil {
			logger.Log.WithField("name", user.Name).Error("FormatMorningData err:", err)
			continue
		}
		err = SendMessage(token, user.WechatId, data.TemplateId, data)
		if err != nil {
			logger.Log.WithField("name", user.Name).Error("SendMessage err:", err)
			continue
		}
		logger.Log.Infof("%s的消息发送成功！", user.Name)
	}
}

// 组装morning 模板的数据
func FormatMorningData(name, region, city string) (data model.Weather, err error) {
	// 获取和风天气regionCode
	regionCode, err := GetRegionCode(region, city)
	if err != nil {
		return
	}
	// 获取实时天气
	weather, err := GetRealtimeWeather(regionCode)
	if err != nil {
		return
	}
	// 获取当日最高，最低温度
	forecast, err := GetWeatherForecast(regionCode)
	if err != nil {
		return
	}
	// 获取空气质量状况
	air, err := GetAirQuality(regionCode)
	if err != nil {
		return
	}
	// 获取每日一句
	quote, err := GetQuote()
	if err != nil {
		return
	}

	// 组装数据
	data.TemplateId = config.Cfg.Template.Weather
	data.Name.SetValue(name)
	data.Today.SetValue(util.GetTodayAndWeek())
	data.Temp.SetValue(weather.Temp + "°C")
	data.City.SetValue(region)
	data.Weather.SetValue(weather.Text)
	data.Wind.SetValue(weather.WindDir + weather.WindScale + "级")
	data.Vis.SetValue(weather.Vis + "公里")
	data.Air.SetValue(air)
	data.MinTemp.SetValue(forecast.MinTemp + "°C")
	data.MaxTemp.SetValue(forecast.MaxTemp + "°C")
	data.NodeEng.SetValue(quote.QuoteEn)
	data.NodeCh.SetValue(quote.QuoteCh)
	return
}
